import cv2
import os


def extract_frames(video_path, output_folder, num_frames=10):
    # 创建输出文件夹
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 打开视频文件
    cap = cv2.VideoCapture(video_path)

    # 获取视频总帧数
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

    # 计算提取帧的间隔
    frame_interval = total_frames // num_frames

    count = 0
    extracted_frames = 0

    while cap.isOpened() and extracted_frames < num_frames:
        ret, frame = cap.read()
        if not ret:
            break

        if count % frame_interval == 0:
            frame_filename = os.path.join(output_folder, f"frame_{extracted_frames + 1}.jpg")
            cv2.imwrite(frame_filename, frame)
            extracted_frames += 1

        count += 1

    cap.release()
    print(f"Extracted {extracted_frames} frames from {video_path}")


def process_videos_in_folders(base_folder):
    # 遍历所有文件夹和文件
    for root, dirs, files in os.walk(base_folder):
        for file in files:
            if file.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')):  # 支持的视频格式
                video_path = os.path.join(root, file)
                output_folder = os.path.join(root, 'extracted_frames')
                extract_frames(video_path, output_folder)


# 使用时将 'your_base_folder' 替换为你的文件夹路径
base_folder =f'H:\抖音下载\船长自驾西藏'
process_videos_in_folders(base_folder)
